package com.xingfudazi.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.xingfudazi.common.core.domain.entity.SysRole;
import com.xingfudazi.common.utils.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 *  配置租户隔离 以及 分页插件
 */
@Configuration
public class MybatisPlusSaasConfig {


    /**
     * 哪些表需要做多租户 表需要添加一个字段 tenant_id
     */
    public static final List<String> TENANT_TABLE = new ArrayList<String>();

    static {
        //1.需要租户隔离的表请在此配置
        TENANT_TABLE.add("bc_contract");
        TENANT_TABLE.add("bc_app");
        TENANT_TABLE.add("bc_contract_access_log");
    }


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                Long userId = SecurityUtils.getUserId();
                return new LongValue(userId);
            }

            @Override
            public String getTenantIdColumn() {
                return "creator";
            }

            // 返回 true 表示不走租户逻辑
            @Override
            public boolean ignoreTable(String tableName) {
                try {
                    Long roleId = SecurityUtils.getLoginUser().getUser().getRoles().get(0).getRoleId();
                    boolean admin = SysRole.isAdmin(roleId);
                    if (admin) {
                        return true;
                    }
                } catch (Exception e) {
                    return true;
                }
                for (String temp : TENANT_TABLE) {
                    if (temp.equalsIgnoreCase(tableName)) {
                        return false;
                    }
                }
                return true;
            }
        }));
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


}
